/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.TX;

import entity.*;
import Helper.Helper_Outlet;
import entity.tta.OutletDataModel;
import exception.ExistException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Chen Zhe, Lu Xiaodi
 */
@Stateless
public class OutletSB implements OutletSBRemote {

    @PersistenceContext()
    EntityManager em;
    private OutletManager manager;
    OutletManager om;
    Outlet outlet;

    public OutletSB() {
    }
    private static final String charset = "!0123456789abcdefghijklmnopqrstuvwxyz";

    public String getRandomString(int length) {
        Random rand = new Random(System.currentTimeMillis());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int pos = rand.nextInt(charset.length());
            sb.append(charset.charAt(pos));
        }
        return sb.toString();
    }

    public void createOutlet(String stakeholderName, String outletName, String phoneNumber, String employeeid, String employeename, String email, String address) throws ExistException {
        //remember to check for duplicate outlet 
        //Create a Outlet Manager
        if (!checkEmployeeId(employeeid)) {
            manager = new OutletManager();
            String password = getRandomString(10);
            manager.create(employeename, email, employeeid, password);
            em.persist(manager);
            //Create new Outlet
            StakeholderFood stakeholder;
            stakeholder = em.find(StakeholderFood.class, stakeholderName);
            Outlet outlet = new Outlet();
            outlet.create(outletName, phoneNumber, stakeholder, manager, address);
            Calendar today = Calendar.getInstance();
            today.setTime(new Date());
            today.add(Calendar.MONTH, 2);
            outlet.setCreateTime(today);
            stakeholder.addOutlet(outlet);
            
            OutletDataModel dataModel = new OutletDataModel();
            outlet.setOutletDataModel(dataModel);
            em.persist(stakeholder);
            em.persist(outlet);
        } else {
            throw new ExistException("Outlet name conflict: " + outletName);
        }
    }

    public boolean checkEmployeeId(String employeeid) {
        om = em.find(OutletManager.class, employeeid);
        if (om == null) {
            return false;
        } else {
            return true;
        }
    }

    public List<Outlet> getAllOutlets() {
        Query query = em.createQuery("SELECT o FROM Outlet AS o");
        return query.getResultList();
    }

    public List<Helper_Outlet> getAllOutletsHelper() {
        List<Outlet> list = this.getAllOutlets();
        if (list == null) {
            return null;
        }
        List<Helper_Outlet> returnList = new ArrayList<Helper_Outlet>();
        for (Outlet o : list) {
            returnList.add(new Helper_Outlet(o.getId(), o.getOutletName(), o.getAddress(),
                    o.getStakeholder().getName(), o.getPhoneNumber()));
        }
        return returnList;
    }

    public void deleteOutlet(Long outletId) {
        outlet = em.find(Outlet.class, outletId);
        StakeholderFood s= outlet.getStakeholder();
        s.getOutlet().remove(outlet);
        em.persist(outlet);
        em.remove(outlet);
    }

    public String updateGeneralInfo(Long outletId, Double noShowFee, Boolean autoConfirm, Integer leadTime,
            Integer bookingWindow) {
        outlet = em.find(Outlet.class, outletId);
        if (outlet == null) {
            return "Outlet not found!";
        } else {
            outlet.setNoShowPenalty(noShowFee);
            outlet.setAutoConfirmReservation(autoConfirm);
            outlet.setLeadTime_Day(leadTime);
            outlet.setBookingWindow(bookingWindow);
            em.persist(outlet);
            em.flush();
            return "General information changed successfully!";
        }
    }

    public List<FoodItem> getFoodMenu(Long outletId) {
        Outlet oe = em.find(Outlet.class, outletId);
        if (oe == null) {
            return null;
        }

        return oe.getFoodMenu();
    }

    public List<FoodItem> getFeaturedFoodItems(Long outletId) {
        List<FoodItem> list = this.getFoodMenu(outletId);
        List<FoodItem> returnList = new ArrayList<FoodItem>();
        for (FoodItem l : list) {
            if (l.getType().equalsIgnoreCase("Featured Dish")) {
                returnList.add(l);
            }
        }
        return returnList;
    }

    public static String booleanToStr(Boolean b) {
        if (b) {
            return "yes";
        } else {
            return "no";
        }
    }

    public Boolean getAutoConfirm(Long outletId) {
        Outlet outlet = em.find(Outlet.class, outletId);
        if (outlet == null) {
            return null;
        }
        return outlet.getAutoConfirmReservation();
    }

    public Integer getLeadTime(Long outletId) {
        Outlet outlet = em.find(Outlet.class, outletId);
        if (outlet == null) {
            return null;
        }
        return outlet.getLeadTime_Day();
    }

    public Integer getBookingWindow(Long outletId) {
        Outlet outlet = em.find(Outlet.class, outletId);
        if (outlet == null) {
            return null;
        }
        return outlet.getBookingWindow();
    }

    public Double getNoShowPenalty(Long outletId) {
        Outlet outlet = em.find(Outlet.class, outletId);
        if (outlet == null) {
            return null;
        }
        return outlet.getNoShowPenalty();
    }
   
    public Outlet getOutlet(Long outletId) {
        Outlet outlet = em.find(Outlet.class, outletId);
        return outlet;
    }

    public List<Outlet> getSpecificOutlet(String o) {
        Query query = em.createQuery("SELECT OBJECT(e) FROM Outlet e where LOCATE(:outletName, e.outletName)>0");
        query.setParameter("outletName", o);
        return query.getResultList();
    }

    public Long searchOutletIdByStr(String[] s) {
        Query query = em.createQuery("SELECT o FROM Outlet o WHERE o.stakeholder.name = :value1"
                + " AND o.outletName= :value2");
        query.setParameter("value1", s[0].trim());
        query.setParameter("value2", s[1].trim());
        List<Outlet> result = query.getResultList();
        if (result.size()!=1) {
            return null;
        } else { 
            return result.get(0).getId();
        }
    }
    
    //added by Randall 13-oct-11 1245hrs
    public List<Outlet> getOutletByStakeholder(String StakeholderID) {
        Query query = em.createQuery("SELECT c FROM Outlet c where c.stakeholder.name = :paramStakeholder");
        query.setParameter("paramStakeholder", StakeholderID);
        return query.getResultList();
    }
    
}
